//************************************************
// File Name: Level0ViewController.m
// Team: Team Epsilon
// Date Created: 2009/07/01
// Purpose: The Tutorial Level of the adventure mode. 
// Change History: 
//   * James, Date: 2009/06/18 Create File
//   * James, Date: 2009/06/20 Adding Controller
//   * James, Date: 2009/06/24 Adding timer
//   * James, Date: 2009/07/01 Adding Objects
//   * James, Date: 2009/07/01 Adding Comments
//   * James, Date: 2009/07/13 Fix bug where object can move to anywhere on the map
//   * Shanna, Date: 2009/07/15 Movement bug fix
//   * JJ, Date: 2009/07/15 Movement buy fix
//   * Mark, Date: 2009/07/15 Major Movement bug fix
//   * JJ, Date: 2009/07/15 Movement buy fix
//   * James, Date: 2009/07/16 Adding comment
// Known Bugs:
//   1. Invalid movement does not work perfectly correct.
//************************************************

#import "Level0ViewController.h"
#import "SecondViewController.h" //to load next level

// implementation of the level view control
@implementation Level0ViewController

// show the popup window
@synthesize alertFlag;

// timer starts
// initial time in miliseconds
@synthesize iniSec;
// check if time's up
@synthesize timeUP;
// check if game is still playing
@synthesize gameIsPlaying;
//timer ends

// view the pop-up windows dialog
@synthesize usageAlertView;

// show the pop-up windows dialog
@synthesize showUsageAlert;

// handle with the nib file to load the objects
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil 
{
    if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) 
	{
		alertFlag=0;
		
        // Custom initialization
    }
    return self;
}

// handle the next level, load the view and objects
- (IBAction) nextlevel:(id)sender 
{
	SecondViewController *game = [[SecondViewController alloc] initWithNibName:@"SecondView" bundle:nil];
	[UIView beginAnimations:nil context:NULL]; 
	[UIView setAnimationDuration:0.5]; 
	[UIView setAnimationTransition:UIViewAnimationTransitionFlipFromRight forView:self.view cache:YES]; 
	[self.view addSubview:game.view]; 
	[UIView commitAnimations];
	
}

// login button
- (IBAction) loginx:(id)sender 
{	
	showUsageAlert = YES;
    [self performSelector:@selector(showUsageAlertDialog) withObject:nil afterDelay:0.0];
	
}


/*
 // The designated initializer. Override to perform setup that is required before the view is loaded.
 - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
 if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
 // Custom initialization
 }
 return self;
 }
 */

/*
 // Implement loadView to create a view hierarchy programmatically, without using a nib.
 - (void)loadView {
 }
 */

/*
 // Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
 - (void)viewDidLoad {
 [super viewDidLoad];
 }
 */

/*
 // Override to allow orientations other than the default portrait orientation.
 - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
 // Return YES for supported orientations
 return (interfaceOrientation == UIInterfaceOrientationPortrait);
 }
 */

// what to show in the pop-up window dialogs
- (void)showUsageAlertDialog
{
    if (showUsageAlert) 
	{
        NSString *message = @"Login to our website!";
        self.usageAlertView = [[UIAlertView alloc] initWithTitle:@"Usage" message:message delegate:self cancelButtonTitle:@"Go!" otherButtonTitles:nil];
		usageAlertView.alpha = .20;
		
        [self.usageAlertView show];
		alertFlag = 1;
    }
}

// how the pop-up window dialog ends
- (void)dismissUsageAlert
{
    [self.usageAlertView dismissWithClickedButtonIndex:-1 animated:YES];
}

// how the pop-up window dialog release from memory
- (void)modalViewCancel:(UIAlertView *)alertView
{
    [alertView release];
}

// message show after click the login button
- (void)modalView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex
{
    if (buttonIndex != -1 && alertFlag ==1) 
	{
        // Open Safari only if the user clicked the 'Launch Safari' button, but not if this
        // delegate method is called by UIKit to cancel it. In that case, buttonIndex is -1.
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"http://code.google.com/p/team-epsilon/"]];
    }
	
    [alertView release];
	
}

// Memory Warning
- (void)didReceiveMemoryWarning 
{
    [super didReceiveMemoryWarning]; // Releases the view if it doesn't have a superview
    // Release anything that's not essential, such as cached data
}



// timmer
//load the timer
- (void)viewDidLoad 
{
	score0=0;
	[countdownLabel setFont:[UIFont fontWithName:@"DBLCDTempBlack" size:30.0]];
	countdownLabel.text = @"0000";
	
	msgLabel.text = @"";
	[self setIniCord];
	
	[super viewDidLoad];
	
}

// Auto rotate if the device changes from portrait to landscape
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation 
{
	// Return YES for supported orientations
	return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

// Deal with allocation/deallocation of memory
- (void)dealloc 
{
	[timer release];
	[super dealloc];
}

// do something after timer finished
-(IBAction)doSomething:(id)sender
{
	timeUP=YES;
}

// update the timer
-(void)updateLabel 
{
	// if the kill is smaller the object the timer will still going
	if(kills>=3)
	{
		isWin=YES;
		timeUP=YES;
	}
	
	iniSec =  iniSec-1  ;
	
	countdownLabel.text = [NSString stringWithFormat:@"%04d ", iniSec];
	
	//if statement indicate the next actions should be taken if time reaches certain range;
	if(iniSec<50)
	{
		countdownLabel.textColor = [UIColor redColor];
		// a simple flashing text effect;
		if (iniSec%4 != 0)
		{
			msgLabel.text = @" TIME IS RUNNING OUT!";
		}
		else 
		{
			
			msgLabel.text = @"";
			
		}
		
	}
	if(iniSec==0)
	{
		iniSec = 200;
		timeUP = YES;
		
	}   
	
}  

// action for start the counter
-(IBAction)startCount:(id)sender
{
	NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
	[prefs setInteger:0	forKey:@"level0"];
	if(gameIsPlaying!=YES)
	{
		//set game time here
		iniSec=200;
		kills = 0;
		isWin = NO;
		[self setIniTime];
		[self resetCord];
		msgLabel.text = @"";
		
		timeUP = NO;
		
		timer = [NSTimer scheduledTimerWithTimeInterval:(0.1) target:self selector:@selector(onTimer) userInfo:nil repeats:YES];	
	}
	
}

//the timer status when running
- (void)onTimer 
{
	gameIsPlaying=YES;
	[self updateLabel];
	// check the boolean in viewController, if it reaches zero, the timer would be stopped.
	if (self.timeUP==YES )
	{
		[timer invalidate];
		gameIsPlaying =NO;
		
		countdownLabel.textColor = [UIColor whiteColor];
		if (isWin==NO)
		{
			NSString *message = @"Please Try Again!";
			UIAlertView *failedAlertView = [[UIAlertView alloc] initWithTitle:@"Failed!" message:message delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
			alertFlag = 2;
			[failedAlertView show];
			
		}
		else
		{
			NSString *message = @"Congratulations!\n";
			UIAlertView *winAlertView = [[UIAlertView alloc] initWithTitle:@"You Win!" message:message delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
			alertFlag = 2;
			[winAlertView show];
			
			
			score0 = iniSec;
			
			NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
			[prefs setInteger:score0 forKey:@"level0"];
		}
		

		
		[self lockEveryThing];
	}
	
}

// every object can not be click
-(void)lockEveryThing
{
	water1.userInteractionEnabled=NO;
	//water2.userInteractionEnabled=NO;
	fire1.userInteractionEnabled=NO;
	fire2.userInteractionEnabled=NO;
	grass1.userInteractionEnabled=NO;
	
}

// Terminate the application
- (void)applicationWillTerminate:(UIApplication *)application 
{
	[timer invalidate];
	gameIsPlaying =NO;
	
}

//set the game time
-(void)setIniTime
{
	// Set the time limit here;
	iniSec = 200;
	
}

//player
// set initial coordinate
-(void)setIniCord
{
	offScreenPoint = CGPointMake(-99, -99);
	
	water1_cord =water1.center;
	grass1_cord = grass1.center;
	fire1_cord = fire1.center;
	fire2_cord = fire2.center;
	
	last_water1_cord =water1.center;
	last_grass1_cord = grass1.center;
	last_fire1_cord = fire1.center;
	last_fire2_cord = fire2.center;
	
	
	
}

// reset the player coordinate
-(void)resetCord
{
	water1.alpha=0.8;
	
	fire1.alpha=0.8;
	
	fire2.alpha=0.8;
	
	grass1.alpha=0.8;
	
	water1.userInteractionEnabled=YES;
	
	
	fire1.userInteractionEnabled=YES;
	
	
	fire2.userInteractionEnabled=YES;
	
	
	grass1.userInteractionEnabled=YES;
	
	
	water1.center = water1_cord;
	
	fire1.center = fire1_cord;
	
	fire2.center = fire2_cord;
	
	grass1.center = grass1_cord;
	
	
	last_water1_cord =water1.center;
	last_grass1_cord = grass1.center;
	last_fire1_cord = fire1.center;
	last_fire2_cord = fire2.center;
	
}

//what will happen when touches
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event 
{
	// get touch event
	if (gameIsPlaying == YES)
	{		
		UITouch *touch = [[event allTouches] anyObject];
		CGPoint touchLocation = [touch locationInView:self.view];
		
		if ([touch view] == water1) 
		{
			// move the image view
			[self.view bringSubviewToFront:water1];
			
			water1.center = touchLocation;
		}
		else if ([touch view] == fire1) 
		{
			[self.view bringSubviewToFront:fire1];
			
			// move the image view
			fire1.center = touchLocation;
		}
		else if ([touch view] == fire2) 
		{
			[self.view bringSubviewToFront:fire2];
			
			// move the image view
			fire2.center = touchLocation;
		}
		else if ([touch view] == grass1) 
		{
			[self.view bringSubviewToFront:grass1];
			
			// move the image view
			grass1.center = touchLocation;
		}
		else 
		{
			
		}
		
	}
	
}


-(int) checkposition: (int) a: (int) b{
	if (a == water1_cord.x && b == water1_cord.y){
	}
    return 0;
}


// what happen while touch the object
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event 
{
	
	UITouch *touch = [touches anyObject];
	
	// If the touch was in the placardView, bounce it back to the center
	if ([touch view] ==  water1) 
	{
		if (abs(water1.center.y - fire1.center.y) < 45 && abs(water1.center.x - fire1.center.x)< 45 && abs(last_water1_cord.y - fire1.center.y)<165 && abs(last_water1_cord.x - fire1.center.x)<165  )
		{
			water1.center = fire1.center;
			last_fire1_cord = water1.center;
			
			fire1.center=offScreenPoint;
			
			fire1.userInteractionEnabled=NO; // the user can't touch it anymore, it has been eaten
			fire1.alpha=0; // undisplay the image;
			kills ++;
			return;
			
		}
		else if (abs(water1.center.y - fire2.center.y) < 45 && abs(water1.center.x - fire2.center.x)< 45 )
		{
			water1.center = fire2.center;
			last_water1_cord = water1.center;
			
			fire2.center=offScreenPoint;
			
			fire2.userInteractionEnabled=NO; // the user can't touch it anymore, it has been eaten
			fire2.alpha=0; // undisplay the image;
			kills ++;
			
			return;
			
		}
		// Disable user interaction so subsequent touches don't interfere with animation
		else 
		{
			
			water1.center = last_water1_cord;
			return;
		}
		
	}		
	else if ([touch view] ==  fire1) 
	{
		if (abs(fire1.center.y - grass1.center.y) < 45 && abs(fire1.center.x - grass1.center.x)< 45 && abs(last_fire1_cord.y - grass1.center.y)<120 && abs(last_fire1_cord.x - grass1.center.x)<120)
		{
			fire1.center = grass1.center;
			last_fire1_cord = fire1.center;
			
			
			grass1.center=offScreenPoint;
			grass1.userInteractionEnabled=NO; // the user can't touch it anymore, it has been eaten
			grass1.alpha=0; // undisplay the image;
			kills ++;
			
			return;
			
		}
		
		// Disable user interaction so subsequent touches don't interfere with animation
		else 
		{
			
			fire1.center = last_fire1_cord;
			return;
		}
		
	}
	
	else if ([touch view] ==  fire2) 
	{
		if (abs(fire2.center.y - grass1.center.y) < 45 && abs(fire2.center.x - grass1.center.x)< 45 )
		{
			fire2.center = grass1.center;
			last_fire2_cord = fire2.center;
			
			grass1.center = offScreenPoint;
			grass1.userInteractionEnabled=NO; // the user can't touch it anymore, it has been eaten
			grass1.alpha=0; // undisplay the image;
			kills ++;
			
			return;
			
		}
		
		// Disable user interaction so subsequent touches don't interfere with animation
		else 
		{
			fire2.center = last_fire2_cord;
			return;
		}	
		
	}		
	else if ([touch view] ==  grass1) 
	{
		if (abs(grass1.center.y - water1.center.y) < 45 && abs(grass1.center.x - water1.center.x)< 45  && abs(last_grass1_cord.y - water1.center.y)<50 && abs(last_grass1_cord.x - water1.center.x)<161)
		{
			grass1.center = water1.center;
			last_grass1_cord = grass1.center;
			
			water1.center=offScreenPoint;
			water1.userInteractionEnabled=NO; // the user can't touch it anymore, it has been eaten
			water1.alpha=0; // undisplay the image;
			kills ++;
			
			return;
			
		}
		
		// Disable user interaction so subsequent touches don't interfere with animation
		else 
		{
			
			grass1.center = last_grass1_cord;
			return;
		}
		
	}
	
}


@end